<template>
    <el-form-item label="设备：">
        <el-select v-model="that.sysRodId">
            <el-option v-for="item in that.localdata"
                       :key="item.value"
                       :label="item.text"
                       :value="item.value"/>
        </el-select>
    </el-form-item>
    <div v-if="that.cameraOnline">
        <el-row :gutter="20"
                :element-loading-text="that.loadingText">
            <el-col :offset="2" :span="10">
                <div class="content">
                    <div class="preview" id="video-container"></div>
                    <!--        <div>-->
                    <!--            <button @click="stop()">stop</button>-->
                    <!--            <button @click="play()">play</button>-->
                    <!--            <button @click="openSound()">openSound</button>-->
                    <!--            <button @click="closeSound()">closeSound</button>-->
                    <!--            <button @click="startSave()">startSave</button>-->
                    <!--            <button @click="stopSave()">stopSave</button>-->
                    <!--            <button @click="capturePicture()">capturePicture</button>-->
                    <!--            <button @click="fullScreen()">fullScreen</button>-->
                    <!--            <button @click="getOSDTime()">getOSDTime</button>-->
                    <!--            <button @click="ezopenStartTalk()">开始对讲</button>-->
                    <!--            <button @click="ezopenStopTalk()">结束对讲</button>-->
                    <!--            <button @click="destroy()">销毁</button>-->
                    <!--        </div>-->
                </div>
            </el-col>
            <el-col :offset="2" :span="10">
                <el-divider>云台控制</el-divider>
                <el-switch
                        v-model="that.deviceStarted"
                        :loading="that.loading"
                        size="large"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        inline-prompt
                        active-text="运行中"
                        inactive-text="已休眠"
                        @change="that.deviceStarted?play():stop()"/>
                <el-divider content-position="left">旋转</el-divider>
                <el-button @click="controlPtz(0)">向上</el-button>
                <el-button @click="controlPtz(1)">向下</el-button>
                <br>
                <br>
                <el-button :icon="ArrowLeft" @click="controlPtz(2)">左转</el-button>
                <el-button @click="controlPtz(-1)">停止</el-button>
                <el-button @click="controlPtz(3)">
                    <span style="vertical-align: middle"> 右转 </span>
                    <el-icon style="vertical-align: middle">
                        <ArrowRight/>
                    </el-icon>
                </el-button>
                <el-divider content-position="left">变焦</el-divider>
                <el-button @click="controlPtz(10)">近焦距</el-button>
                <el-button @click="controlPtz(11)">远焦距</el-button>
                <el-divider content-position="left">缩放</el-divider>
                <el-button :icon="ZoomIn" @click="controlPtz(8)">放大</el-button>
                <el-button :icon="ZoomOut" @click="controlPtz(9)">缩小</el-button>
            </el-col>
        </el-row>
        <el-divider content-position="left">视频/图片采集</el-divider>
        <el-button type="primary" @click="dialogTable={visible: true,content: '即时录制'}">
            即时录制
        </el-button>
        <el-button type="primary" @click="dialogTable={visible: true,content: '预约录制'}">
            预约录制
        </el-button>
        <el-button type="primary" @click="dialogTable={visible: true,content: '批量预约录制'}">
            批量预约录制
        </el-button>
        <el-button type="warning" disabled @click="dialogTable={visible: true,content: 'InstantRecord'}">
            即时抓图
        </el-button>
        <el-button type="warning" @click="dialogTable={visible: true,content: '预约抓图'}">
            预约抓图
        </el-button>
        <el-button type="warning" @click="dialogTable={visible: true,content: '批量预约抓图'}">
            批量预约抓图
        </el-button>

        <el-dialog v-model="dialogTable.visible"
                   :title="dialogTable.content"
                   width="60%">
            <InstantRecord @closeView="dialogTable.visible=false" v-if="dialogTable.content==='即时录制'"/>
            <ScheduleRecord @closeView="dialogTable.visible=false" v-if="dialogTable.content==='预约录制'"/>
            <ScheduleRecordBatch @closeView="dialogTable.visible=false" v-if="dialogTable.content==='批量预约录制'"/>
            <ScheduleCapture @closeView="dialogTable.visible=false" v-if="dialogTable.content==='预约抓图'"/>
            <ScheduleCaptureBatch @closeView="dialogTable.visible=false" v-if="dialogTable.content==='批量预约抓图'"/>
        </el-dialog>
    </div>
    <div v-else>设备不在线</div>
</template>

<script setup>
import axios from 'axios'
import EZUIKit from 'ezuikit-js';
import {inject, onMounted, reactive, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {ArrowLeft, ArrowRight, ZoomIn, ZoomOut,} from '@element-plus/icons-vue'
import ScheduleCapture from "@/pages/camera/ScheduleCapture.vue";
import ScheduleRecord from "@/pages/camera/ScheduleRecord.vue";
import ScheduleRecordBatch from "@/pages/camera/ScheduleRecordBatch.vue";
import InstantRecord from "@/pages/camera/InstantRecord.vue";
import ScheduleCaptureBatch from "@/pages/camera/ScheduleCaptureBatch.vue";


// 使用 inject 获取全局变量
const $host = inject('$host');
axios.defaults.baseURL = $host

const that = reactive({
    loading: false,
    loadingText: 'fd',
    deviceStarted: true,
    sysRodId: 1,
    localdata: [{
        value: 'A',
        text: "开发区A杆"
    }, {
        value: 'B',
        text: "开发区B杆"
    }],
    cameraOnline: true,
})

const dialogTable = ref({
    visible: false,
    content: ''
})

/**
 * 云台控制
 * @param direction 操作命令：-1-停止，0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
 */
function controlPtz(direction) {
    axios({
        method: 'PUT',
        url: '/device/ptz/' + that.sysRodId,
        params: {
            direction: direction,
        }
    }).then(({data}) => {
        if (data.data.code === 200) {
            ElMessage({
                message: data.data.msg,
                type: 'success',
            })
        }
    })
}

watch(
    () => that.sysRodId,
    (newValue) => {
        initPlayer()
    },
    {deep: true}
)

var player = null;
onMounted(() => {
    console.log('mounted...');
    // 获取所有杆
    axios({
        method: 'GET',
        url: '/rod',
    }).then(({data}) => {
        that.localdata = data.data.map(item => {
            return {
                value: item.id,
                text: item.projectName
            }
        })
    })

    // 初始化摄像头
    if (typeof window.EZUIKit !== 'undefined') {
        console.log('defined EZUIKit...');
        initPlayer();
    } else {
        console.log('undefined EZUIKit...');
        // 动态引入较大类库避免影响页面展示
        const script = document.createElement('script')
        // view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
        script.src = 'static/ezuikit.js'
        script.onload = initPlayer.bind(this)
        document.head.appendChild(script)
    }
})

function initPlayer() {
    console.log('initPlayer...');
    axios({
        method: 'GET',
        url: '/accessToken'
    }).then(({data}) => {
        let accessToken = data.data
        axios({
            method: 'GET',
            url: '/live/address/' + that.sysRodId,
        }).then(({data}) => {
            if (data.code === 200) {
                that.cameraOnline = true
                let liveAddress = data.data
                const windowWidth = 600;
                player = new EZUIKit.EZUIKitPlayer({
                    id: 'video-container', // 视频容器ID
                    accessToken: accessToken,
                    url: liveAddress,
                    // simple - 极简版; pcLive-pc直播；pcRec-pc回放；mobileLive-移动端直播；mobileRec-移动端回放;security - 安防版;voice-语音版;
                    //template: 'simple',
                    // plugin: ['talk'], // 加载插件，talk-对讲
                    width: windowWidth,
                    height: windowWidth * 2 / 3,
                });
                window.player = player;
            } else {
                that.cameraOnline = false
                console.log(data.data.msg)
            }
        })
    })
}

function play() {
    that.loading = true
    that.loadingText = "启动中。。"
    var playPromise = player.play();
    playPromise.then((data) => {
        console.log("promise 获取 数据", data)
        that.deviceStarted = true
        ElMessageBox.alert('摄像头已启用', '系统提示', {type: 'success', center: true,})
    }).catch(() => {
        that.deviceStarted = false
        ElMessageBox.alert('启动失败，请检查设备及客户端网络', '系统提示', {type: 'error', center: true,})
    }).finally(() => {
        that.loading = false
    })
}

function stop() {
    that.loading = true
    that.loadingText = "关闭中。。"
    var stopPromise = player.stop();
    stopPromise.then((data) => {
        console.log("promise 获取 数据", data)
        that.loading = false
        that.deviceStarted = false
        ElMessageBox.alert('摄像头已休眠', '系统提示', {type: 'warning', center: true,})
    })
}

function getOSDTime() {
    var getOSDTimePromise = player.getOSDTime();
    getOSDTimePromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}

function capturePicture() {
    var capturePicturePromise = player.capturePicture(`${new Date().getTime()}`);
    capturePicturePromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}

function openSound() {
    var openSoundPromise = player.openSound();
    openSoundPromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}

function closeSound() {
    var openSoundPromise = player.closeSound();
    openSoundPromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}

function startSave() {
    var startSavePromise = player.startSave(`${new Date().getTime()}`);
    startSavePromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}

function stopSave() {
    var stopSavePromise = player.stopSave();
    stopSavePromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}

function ezopenStartTalk() {
    player.startTalk();
}

function ezopenStopTalk() {
    player.stopTalk();
}

function fullScreen() {
    player.fullScreen();
}

function destroy() {
    var destroyPromise = player.destroy();
    destroyPromise.then((data) => {
        console.log("promise 获取 数据", data)
    })
}
</script>

<style>
.content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.preview {
    background-color: black;
}
</style>
